//
//  LKContinuInvestOrderListViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/4.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKContinuInvestOrderListViewController.h"
#import "LKMyChooseCustomerViewController.h"
#import "LKWorkOrderListCell.h"
#import "LKSearchBar.h"
#import "LKMyOrderCheckDetailViewController.h"
@interface LKContinuInvestOrderListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property(nonatomic,strong)LKBaseTableview *tableview;
@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)LKSearchBar *searchBar;
@property(nonatomic,strong)NSMutableArray *dataListArray;
@property(nonatomic,assign)BOOL isHandInput;
@end

@implementation LKContinuInvestOrderListViewController
-(LKBaseTableview *)tableview{
    if (!_tableview) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 46)];
        _topView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_topView];
        //创建searchBar
        LKSearchBar *searchBar = [[LKSearchBar alloc] initWithFrame:CGRectMake(8, 8, WIDTH - 16,30)];
        //默认提示文字
        searchBar.placeholder = @"输入合同编号查询";
//         searchBar.delegate = self;
        [_topView addSubview:searchBar];
        self.searchBar = searchBar;
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 58, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - 58) style:UITableViewStylePlain registercellClasss:@[@"LKWorkOrderListCell"]];

        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor = [UIColor whiteColor];
        _tableview.emptyDataSetDelegate = self;
        _tableview.emptyDataSetSource = self;
    }
    return _tableview;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHandInput = NO;
    [self.view addSubview:self.tableview];
    [self getContinueOrderList];
//    self.tableview.estimatedRowHeight = 200;

    // Do any additional setup after loading the view.
   
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    WS(weakSelf)
    self.navigationItem.title = @"订单列表";
    
//    if (self.handInputOrderApply) {
//        return;
//    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitle:@"手动输入" forState:UIControlStateNormal];
    [btn setTitleColor:blueDefault forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入要续投的合同编号" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField *contentTf = alert.textFields.firstObject;
            NSLog(@"输入内容%@",contentTf.text);
//            [weakSelf judgeGetIsExitWithContractCode:contentTf.text];
//            weakSelf.handInputOrderApply = YES;
            
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:contentTf.text,@"ContractCode",@(NO),@"IsContinuedInvestment", nil];
            
            NSLog(@"参数%@",param);
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:ContinueOrderInvestJudgeUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                if ([responseObject[@"result"][@"isInSystem"] integerValue]) {
                    [SVProgressHUD showInfoWithStatus:@"该单已存在系统中"];
                    return ;
                }else{
                    if (weakSelf.orderApplyHandBlock) {
                        weakSelf.orderApplyHandBlock(contentTf.text,YES);
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                        return;
                    }
                    
                    LKMyChooseCustomerViewController *vc = [[LKMyChooseCustomerViewController alloc] init];
                    vc.addContinueIdValue = ^(NSString *customerId) {

                    };
                    vc.isAddContinueHand = YES;
                    vc.contractCode = contentTf.text;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    
                    


                }
            } failure:^(NSString * _Nullable errorMessage) {
//                if (weakSelf.orderApplyHandBlock) {
//                    weakSelf.orderApplyHandBlock(contentTf.text,YES);
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
//                }
            }];
            
            
            
            
            
            

//            if (self.contractCodeBlock) {
//                LKOrderModel *model = [LKOrderModel modelWithDictionary:@{}];
//                model.contractCode = contentTf.text;
//                self.contractCodeBlock(model);
//            }
//            [weakSelf.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }];

    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataListArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKWorkOrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWorkOrderListCell"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [cell.labelsView.tableview addGestureRecognizer:tap];
    WS(weakSelf);
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//        if (weakSelf.isAddContinueOrder) {
//            if (weakSelf.contractCodeBlock) {
//                LKOrderModel *model = self.dataListArray[indexPath.section];
//                weakSelf.contractCodeBlock(model.contractCode,model.customerId,model.customerCode);
//                [weakSelf.navigationController popViewControllerAnimated:YES];
//            }
//
//        }else{
//            LKMyOrderCheckDetailViewController *vc = [[LKMyOrderCheckDetailViewController alloc] init];
//            [weakSelf.navigationController pushViewController:vc animated:YES];
//        }
        if (weakSelf.contractCodeBlock) {
            LKOrderModel *model = self.dataListArray[indexPath.section];
            weakSelf.contractCodeBlock(model);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
    cell.model = self.dataListArray[indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.editBtn.hidden = YES;
    cell.deleteBtn.hidden  = YES;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 250;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 13;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (self.isAddContinueOrder) {
//        if (self.contractCodeBlock) {
//            LKOrderModel *model = self.dataListArray[indexPath.section];
//            self.contractCodeBlock(model.contractCode,model.customerId,model.customerCode);
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//
//    }else{
//        LKMyOrderCheckDetailViewController *vc = [[LKMyOrderCheckDetailViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    if (self.contractCodeBlock) {
        LKOrderModel *model = self.dataListArray[indexPath.section];
        self.contractCodeBlock(model);
        [self.navigationController popViewControllerAnimated:YES];
    }
}
/**
 判断续投订单是否在系统中
 */
-(void)judgeGetIsExitWithContractCode:(NSString *)contractCode{
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:contractCode,@"ContractCode",@(YES),@"IsContinuedInvestment", nil];
    
    NSLog(@"参数%@",param);
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:ContinueOrderInvestJudgeUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"result"][@"isInSystem"] integerValue]) {
            [SVProgressHUD showInfoWithStatus:@"该单已存在系统中"];
        }else{
            
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/**
 获取可续投订单列表
 */
-(void)getContinueOrderList{
    NSString *url;
    if (self.isAddContinueOrder) {
        self.addOrderModel.ContractCode = @"";
        url = getContinuInvestUrl;
    }else{
        url = getCanApplyContinueInvestUrl;
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_addOrderModel.ContractCode,@"ContractCode", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSArray *oderArra = responseObject[@"result"];
        for (NSDictionary *dic in oderArra) {
            LKOrderModel *model = [LKOrderModel modelWithDictionary:dic];
            [self.dataListArray addObject:model];
        }
        [self.tableview reloadData];
        
        
    } failure:^(NSString * _Nullable errorMessage) {
     
        [SVProgressHUD showInfoWithStatus:errorMessage];
        
    }];
}
-(NSMutableArray *)dataListArray{
    if (!_dataListArray) {
        _dataListArray = [[NSMutableArray alloc] init];
    }
    return _dataListArray;
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
        searchBar.showsCancelButton = YES;
}
//-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//    searchBar.showsCancelButton = NO;
//
//}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"SearchButton");
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    //    [searchBar setShowsCancelButton:NO animated:YES];
    //    [self.searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
